<?php
declare(strict_types=1);

namespace Modules\Web\Service;

use HiCommon\Repository\ExpressRepository;
use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\StoreOrderGoodsRepository;
use HiCommon\Repository\StoreOrderRefundRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Service\PayRefundService;

class GoodsOrderService extends BaseService
{
    /**
     * 积分商品订单列表
     * yang 2019 11 04
     */
    public function get_mall_order_list(array $search)
    {
        try {
            $shop_id = get_web_shop_id();//门店id

            $arr_search['shop_id'] = $shop_id;
            if ($search['status'] == 1) { //待支付
                $arr_search['status'] = 1;
                $arr_search['pay_status'] = 1;
            } elseif ($search['status'] == 2) { //待发货
                $arr_search['status'] = 1;
                $arr_search['pay_status'] = 2;
            } elseif ($search['status'] == 3) { //待签收
                $arr_search['status'] = 2;
            }

            if (!empty($search['date_time'])) {
                $arr_search['created_at'] = $search['date_time'];
            }
            $arr_option['with'] = ['getGoodsInfo', 'product_info'];

            $listAll = OrderMallRepository::get_list_by_where($arr_search, $arr_option);
            $arr_list = list_page_data($listAll);

            $list = [];
            if ($arr_list['data']) {
                foreach ($arr_list['data'] as $key => $item) {
                    $list[] = array(
                        'order_id' => $item['id'],
                        'order_no' => $item['order_no'],
                        'goods_logo' => $item['product_info']['pic']['full_src'],
                        'goods_name' => $item['get_goods_info']['name'],//商品名称
                        'goods_specs' => $item['product_info']['specs']['name'],//商品规格
                        'created_at' => $item['created_at'],
                        'order_integral' => $item['order_integral'],
                        'pay_status' => $item['pay_status'],
                        'status' => $item['status'],
                        'state' => OrderMallRepository::order_status($item['status'], $item['pay_status'])
                    );
                }
            }

            return hello_success('获取成功！', ['list' => $list, 'page' => $arr_list['page_data']]);

        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     * 积分商品订单详情
     * yang 2019 11 04
     */
    public function get_mall_order_info(int $oid)
    {
        try {
            if (empty($oid)) {
                return hello_error('订单id不能为空');
            }
            //获取订单详情
            $arr_option['with'] = ['getGoodsInfo', 'getUserInfo', 'getAddressInfo', 'product_info', 'getExpressInfo'];
            $order_obj = OrderMallRepository::get_one((int)$oid, (array)$arr_option);

            if ($order_obj->first()) {
                $detail = $order_obj->toArray();
                $res = [
                    'order_id' => $detail['id'],
                    'order_no' => $detail['order_no'],
                    'status' => $detail['status'],
                    'pay_time' => $detail['pay_time'],
                    'pay_status' => $detail['pay_status'],
                    'order_integral' => $detail['order_integral'],
                    'remark' => $detail['remark'],
                    'goods_id' => $detail['goods_id'],
                    'goods_name' => $detail['get_goods_info']['name'],
                    'goods_num' => $detail['goods_num'],
                    'goods_integral' => $detail['goods_integral'],
                    'goods_integral_total' => $detail['order_integral'],
                    'goods_pic' => $detail['product_info']['pic']['full_src'],
                    'goods_specs' => $detail['product_info']['specs']['name'],
                    'receiving_time' => $detail['receiving_time'],
                    'created_at' => $detail['created_at'],
                    'delivery_price' => '0.00',
                    'delivery_no' => $detail['delivery_no'],
                    'express_name' => $detail['get_express_info']['name'],
                    'delivery_time' => $detail['delivery_time'],
                    'address_info' => $detail['get_address_info'],
                    'get_user_info' => $detail['get_user_info'],
                ];

                return hello_success('获取成功！', $res);
            } else {
                return hello_error('订单不存在');
            }
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     * 确认发货
     * yang 2019 11 04
     */
    public function send_mall_goods(array $arrInput)
    {
        try {
            if (empty($arrInput['id'])) {
                return hello_error('订单id不能为空');
            }
            $map = ['id' => intval($arrInput['id'])];
            $arr_input = [
                'status' => 2,
                'xpress_id' => intval($arrInput['xpress_id']),
                'delivery_no' => $arrInput['delivery_no'],
                'delivery_time' => date('Y-m-d H:i:s')
            ];

            $res = OrderMallRepository::edit_one((array)$map, (array)$arr_input);

            if ($res) {
                return hello_success('发货成功！');
            } else {
                return hello_error('发货失败！');
            }

        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**********************************普通订单及处理************************************/
    /**
     * 退货状态处理
     */
    public function check_apply_state($order_refund)
    {
        $apply_type = $order_refund['apply_type'];
        $apply_state = $order_refund['apply_state'];
        if ($apply_type == 3 && $apply_state == 1) {
            return '申请退货-退款';
        } elseif ($apply_type == 2 && $apply_state == 1) {
            return '申请退货-退款';
        } elseif ($apply_type == 1 && $apply_state == 1) {
            return '申请退款';
        } elseif ($apply_state == 2) {
            return '已通过';
        } elseif ($apply_state == 3) {
            return '已拒绝';
        } elseif ($apply_state == 4) {
            return '已退款';
        }
    }

    /**
     * 普通商品订单列表
     * 2019 11 05
     */
    public function get_store_order_list($data)
    {
        try {
            $shop_id = get_web_shop_id();//门店id

            $arr_where['shop_id'] = $shop_id;
            $status = intval($data['status']);
            $time = $data['date_time'];
            $user_id = $data['user_id'];

            if (!empty($status)) {
                if ($status == 1) { //待支付
                    $arr_where['status'] = 1;
                    $arr_where['pay_status'] = 1;
                } elseif ($status == 2) {//待发货
                    $arr_where['status'] = 1;
                    $arr_where['pay_status'] = 2;
                } elseif ($status == 3) {//待收货
                    $arr_where['status'] = 2;
                } elseif ($status == 4) {//已评价
                    $arr_where['status'] = 4;
                }
            }
            if (!empty($time)) {
                $arr_where['created_at'] = $time;
            }
            if (!empty($user_id)) {
                $arr_where['user_id'] = $user_id;
            }

            $arr_option['with'] = ['getOrderGoods'];
            $arr_list = StoreOrderRepository::get_list_by_where($arr_where, $arr_option);
            $list = list_page_data($arr_list);

            $order['list'] = [];
            foreach ($list['data'] as $key => $value) {
                $order['list'][] = [
                    'id' => $value['id'],
                    'order_type' => $value['order_type'],
                    'order_no' => $value['order_no'],
                    'order_amount' => $value['order_amount'],
                    'created_at' => $value['created_at'],
                    'goods_total' => $value['goods_num'],
                    'coupon_price' => $value['coupon_price'],
                    'status' => $value['status'],
                    'pay_status' => $value['pay_status'],
                    'order_status' => StoreOrderRepository::order_status($value['status'], $value['pay_status']),
                    'order_goods' => self::goods_data_handle($value['get_order_goods'])
                ];
            }

            $order['page'] = $list['page_data'];

            return hello_success('获取成功！', $order);
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     * 订单商品数据处理
     * @param $goods_data
     * @param array $comment
     * @return array
     */
    public function goods_data_handle($goods_data, $comment = [])
    {
        $commentData = [];
        foreach ($comment as $key => &$value) {
            $images = [];
            if($value['images']){
                foreach (explode(',', $value['images']) as $item){
                    $images[] = oss_full_url($item);
                }
            }
            $value['images'] = $images;
            $commentData[$value['goods_id']] = $value;
        }

        $goods = [];
        foreach ($goods_data as $ky => $val) {
            if (array_key_exists($val['goods_id'], $commentData)) {
                $is_comment = true;
                $comm = $commentData[$val['goods_id']];
            } else {
                $is_comment = false;
                $comm = (object)[];
            }

            $goods[] = [
                'goods_id' => $val['goods_id'],
                'goods_price' => $val['goods_price'],
                'goods_num' => $val['goods_num'],
                'goods_name' => $val['goods_product']['goods_info']['name'],
                'goods_pic' => $val['goods_product']['pic']['full_src'],
                'goods_specs' => $val['goods_product']['specs']['name'],
                'is_refund' => $val['is_refund'],
                'is_comment' => $is_comment,
                'comment' => $comm,
                'sale_status' => self::goods_refund_status($val['goods_refund_status']['order_refund'])
            ];
        }

        return $goods;
    }

    /**
     * 获取普通商品订单详情
     * 2019 11 08
     */
    public function get_store_order_info(int $oid)
    {
        try {
            if (empty($oid)) {
                return hello_error('订单id不能为空');
            }
            $arr_option['with'] = ['getOrderGoods', 'getUser', 'getAddress', 'getExpress', 'goods_comment'];
            $detail = StoreOrderRepository::get_one((int)$oid, $arr_option);

            if ($detail->first()) {
                $data = $detail->toArray();
                $data['order_status'] = StoreOrderRepository::order_status($data['status'], $data['pay_status']);
                $data['get_order_goods'] = self::goods_data_handle($data['get_order_goods'], $data['goods_comment']);

                unset($data['goods_comment']);
                return hello_success('获取成功！', $data);
            }
            return hello_error('订单不存在！');
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     * 订单操作
     * 2019 11 09
     */
    public function store_order_operation(array $data)
    {
        try {
            if (empty($data['id'])) {
                return hello_error('订单id不能为空');
            }

            $order_id = (int)$data['id'];//订单id
            if ($data['type'] == 1) { //取消订单

                $up_data = [
                    'status' => 5, 'order_status' => 5, 'cancel_reason_id' => 0,
                    'cancel_time' => date('Y-m-d H:i:s', time())
                ];
                StoreOrderRepository::edit_one((array)['id' => $order_id], (array)$up_data);//取消订单
                StoreOrderRepository::cancelOrderBackStock((int)$order_id);//回收库存

                //消息通知
                $dataNotice = [
                    'notice_type' => 'ptshp_order_message_push',
                    'order_id' => $order_id,
                    'type' => 37,
                    'title' => '取消订单通知',
                    'content' => '已被商家取消。'
                ];
                predis_notice_queue_in($dataNotice);

            } elseif ($data['type'] == 2) {//确认发货
                if (empty($data['express']['id'])) {
                    return hello_error('快递公司id不能为空');
                }
                if (empty($data['express']['number'])) {
                    return hello_error('快递单号不能为空');
                }

                $map = ['id' => $order_id];
                $up_data = [
                    'xpress_id' => (int)$data['express']['id'],
                    'delivery_no' => $data['express']['number'],
                    'delivery_time' => date('Y-m-d H:i:s'),
                    'status' => 2
                ];

                StoreOrderRepository::edit_one($map, $up_data);

                //消息推送
                $express = ExpressRepository::get_one((int)$data['express']['id'], ['field' => 'name'])->toArray();
                $dataNotice = [
                    'notice_type' => 'ptshp_order_message_push',
                    'order_id' => $order_id,
                    'type' => 30,
                    'title' => '商品发货通知',
                    'content' => '已通过' . $express['name'] . '发货。'
                ];
                predis_notice_queue_in($dataNotice);

            } else {
                return hello_error('操作状态有误');
            }

            return hello_success('操作成功');
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     * 普通商品订单售后（申请退货退款列表）
     * 2019 11 05
     */
    public function store_order_sale_list($data)
    {
        try {
            $shop_id = get_web_shop_id();//门店id

            $where['shop_id'] = $shop_id;//门店id
            if (!empty($data['date_time'])) {
                $arr_option['whereBetween'] = [$data['date_time'], $data['date_time'] . ' 23:59:59'];
            }

            $arr_option['where'] = $where;
            $arr_option['with'] = ['get_order_refund_goods', 'get_user'];

            $arr_list = StoreOrderRefundRepository::get_list_api($arr_option);
            $list = list_page_data($arr_list);

            $order['list'] = [];
            foreach ($list['data'] as $key => $value) {
                $goods = [];
                $goods_total = 0;
                foreach ($value['get_order_refund_goods'] as $ky => $val) {
                    $goods_info = $val['order_goods'];
                    $goods[] = [
                        'goods_id' => $goods_info['goods_id'],
                        'goods_price' => $goods_info['goods_price'],
                        'goods_num' => $goods_info['goods_num'],
                        'goods_name' => $goods_info['goods_product']['goods_info']['name'],
                        'goods_pic' => $goods_info['goods_product']['pic']['full_src'],
                        'goods_specs' => $goods_info['goods_product']['specs']['name'],
                        'is_refund' => $goods_info['is_refund'],
                    ];
                    $goods_total += $goods_info['goods_num'];
                }
                $sale_status = ['apply_type' => $value['apply_type'], 'apply_state' => $value['apply_state']];
                $order['list'][] = [
                    'id' => $value['id'],
                    'refund_no' => $value['refund_no'],
                    'refund_amount' => $value['refund_amount'],
                    'created_at' => $value['created_at'],
                    'user_phone' => $value['get_user']['phone'],
                    'user_name' => $value['get_user']['nickname'] ?? $value['get_user']['username'],
                    'goods_total' => $goods_total,
                    'sale_status' => self::check_apply_state($sale_status),
                    'order_goods' => $goods,
                ];
            }

            $order['page'] = $list['page_data'];

            return hello_success('获取成功！', $order);
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     * 普通商品售后订单详情
     * 2020-04-13
     */
    public function store_order_sale_info(int $n_id)
    {
        try {
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }

            //查询
            $arr_option['with'] = ['get_order_refund_goods', 'get_user', 'refund_reason_id', 'store_order'];
            $res = StoreOrderRefundRepository::get_one($n_id, $arr_option)->toarray();
            if (empty($res)) {
                return hello_error('查询失败');
            }
            $refund_msg['refund_reason'] = $res['refund_reason'];
            $refund_msg['picture'] = null;
            if (!empty($res['picture'])) {
                $picture = json_decode($res['picture']);
                foreach ($picture as $key => $value) {
                    $refund_msg['picture'][] = oss_full_url($value);
                }
            }
            $refund_goods = [];
            $goods_total = 0;
            foreach ($res['get_order_refund_goods'] as $item) {
                $refund_status = [
                    'apply_type' => $res['apply_type'],
                    'apply_state' => $res['apply_state'],
                ];

                $refund_goods[] = [
                    'goods_name' => $item['order_goods']['goods']['name'],
                    'goods_num' => $item['order_goods']['goods_num'],
                    'goods_price' => $item['order_goods']['goods_price'],
                    'goods_pic' => $item['order_goods']['goods_product']['pic']['full_src'],
                    'goods_product' => $item['order_goods']['goods_product']['specs']['name'],
                    'refund_status' => self::goods_refund_status($refund_status)
                ];
                $goods_total += $item['order_goods']['goods_num'];
            }
            $sale_status = ['apply_type' => $res['apply_type'], 'apply_state' => $res['apply_state']];
            //基础数据
            $result = [
                'refund_id' => $res['id'],
                'refund_no' => $res['refund_no'],
                'apply_type' => $res['apply_type'],
                'apply_state' => $res['apply_state'],
                'refund_amount' => $res['refund_amount'],
                'refund_type' => $res['store_order']['pay_type'],
                'refund_msg' => $refund_msg,
                'refund_goods' => $refund_goods,
                'user_msg' => $res['get_user'],
                'refund_reason' => $res['refund_reason_id']['reason'],
                'created_at' => $res['created_at'],
                'deal_at' => $res['deal_at'],
                'goods_total' => $goods_total,
                'is_logistics' => empty($res['express_id']) ? false : true,
                'sale_status' => self::check_apply_state($sale_status),
            ];

            return hello_success('查询成功', $result);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 商品退单状态
     */
    public function goods_refund_status($data)
    {
        if (!empty($data)) {
            $type = $data['apply_type'] == 1 ? '款' : '货';
            if ($data['apply_state'] == 1) {
                return '申请退' . $type;
            } elseif ($data['apply_state'] == 2) {
                return '申请通过';
            } elseif ($data['apply_state'] == 3) {
                return '被驳回';
            } elseif ($data['apply_state'] == 4) {
                return '已退款';
            }
        }

        return '';
    }

    /**
     * 普通商品售后操作
     * 2020-04-13
     */
    public function store_order_sale_handle($data)
    {
        try {
            $refund_id = intval($data['refund_id']);
            $handle_type = intval($data['handle_type']);
            if (empty($refund_id)) {
                return hello_error('退单id不能为空');
            }
            //查询
            $arr_option['with'] = ['get_refund_price', 'store_order'];
            $refund_ary = StoreOrderRefundRepository::get_one($refund_id, $arr_option)->toarray();

            if ($handle_type == 1) {//同意申请

                $up_array = ['apply_state' => 2, 'deal_at' => date('Y-m-d H:i:s')];

                self::check_goods_all_back((int)$refund_ary['store_order_id']);

                //消息通知
                $dataNotice = [
                    'notice_type' => 'ptshp_sales_message_push',
                    'refund_order_id' => $refund_id,
                    'type' => 51,
                    'title' => '同意申请通知',
                    'content' => '售后申请商家已同意。'
                ];
                predis_notice_queue_in($dataNotice);

            } elseif ($handle_type == 2) {//拒绝申请

                $up_array = ['apply_state' => 3, 'deal_at' => date('Y-m-d H:i:s')];

                foreach ($refund_ary['get_refund_price'] as $key => $value) {
                    StoreOrderGoodsRepository::edit_one(['id' => $value['get_order_goods']['id'], 'is_refund' => 0]);
                }

                //消息通知
                $dataNotice = [
                    'notice_type' => 'ptshp_sales_message_push',
                    'refund_order_id' => $refund_id,
                    'type' => 50,
                    'title' => '拒绝申请通知',
                    'content' => '售后申请已被商家拒绝。'
                ];
                predis_notice_queue_in($dataNotice);

            } elseif (!empty($refund_ary['get_refund_price']) && $handle_type == 3) {//确认退款

                $s_order_sn = $refund_ary['store_order']['order_no'];//订单编号
                $s_refund_sn = $refund_ary['refund_no'];//退单编号

                self::check_goods_all_back((int)$refund_ary['store_order_id'], 7);

                //退款处理
                return PayRefundService::api_online_pay_refund($s_order_sn, $s_refund_sn);
            }

            //更新退单状态
            StoreOrderRefundRepository::edit_one_by_where(['id' => $refund_id], (array)$up_array);

            return hello_success('操作成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /***
     * 检查该订单的所有商品是否全部退单
     * @param int $order_id
     * @param int $status
     */
    public function check_goods_all_back(int $order_id, $status = 9)
    {
        $arr_option = ['with' => ['getOrderGoods2'], 'field' => ['id']];
        $res = StoreOrderRepository::get_one($order_id, $arr_option)->toarray();
        if (min(array_column($res['get_order_goods2'], 'is_refund')) == 1) {
            //商品全部退还更新主变订单状态为已退货已退款
            StoreOrderRepository::change_one_state($order_id, $status);
        }
    }

}